﻿using Business.Core.Annotations;
using Business.Data;
using Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ProjectManager.User;
using ProjectManager.User.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ProjectManagerSys
{
    /// <summary>
    /// 用户消息
    /// </summary>
    public class NoticeMerber : Common.BusinessBase
    {
        [Doc("消息列表", Group = "用户消息")]
        public virtual async Task<dynamic> NoticeList(int page, int limit, string title,DateTime? startTime, DateTime? endTime)
        {
            try
            {
                using (var con = Data.DB.GetConnection())
                {

                    var list = con.MANAGER_NOTICE.AsQueryable();
                    //权限
                    AuthInfo authinfo = Logins.Authorize();

                    list = list.Where(p => p.ACTIVE == 1 && p.RECEIVEUSERID == authinfo.userid);
                    if (string.IsNullOrWhiteSpace(title) == false) //任务名称
                        list = list.Where(p => p.DETAIL.Contains(title));
                    
                    list = startTime.HasValue && endTime.HasValue ? list = list.Where(p => p.CREATETIME >= startTime && p.CREATETIME <= endTime) : list;
                    list = list.OrderByDescending(p => p.CREATETIME);

                    var pageData = list.GetPaging(page, limit);

                    var result = new { code = 0, msg = "", count = pageData.Count, data = pageData.Data };

                    IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                    timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                    return JsonConvert.SerializeObject(result, Formatting.Indented, timeFormat);
                }
            }
            catch (Exception ex) { }
            return null;
        }

        [Doc("是否有新的任务", Group = "用户消息")]
        public virtual async Task<dynamic> isNewNotice()
        {
            var flag = false;
            using (var con = Data.DB.GetConnection())
            {
                AuthInfo authinfo = Logins.Authorize();
                var list = con.MANAGER_NOTICE.Where(c=>c.ACTIVE==1 && c.ISREAD==0 && c.RECEIVEUSERID == authinfo.userid).ToList();
                if (list.Count > 0) flag = true;
            }
            return JsonConvert.SerializeObject(flag);
        }

        [Doc("设置任务为已读", Group = "用户消息")]
        public virtual async Task<dynamic> SetReader()
        {
            string sql = string.Format("update MANAGER_NOTICE set ISREAD=1,UPDATETIME=sysdate where ISREAD=0");
            using (var con = Data.DB.GetConnection())
            {
                con.ExecuteNonQuery(sql);
            }
            return null;   
        }
    }
}
